<?php

namespace App\Http\Controllers\Report;

use App\Exports\ReportRegionIndicatorExport;
use App\Http\Conf\ResultInfo;
use App\Http\Controllers\Controller;
use App\Http\Models\Business\CacheInvoiceRegion;
use App\Http\Models\Business\InvoiceDetails;
use App\Http\Models\Report\ReportRegionIndicator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class RegionIndicatorProgress extends Controller
{
    public function index(Request $request)
    {
        $year = is_numeric($request->year) ? $request->year : date('Y', time());
        $month = is_numeric($request->month) ? $request->month : date('m', time());

        $report_region_indicator = new ReportRegionIndicator($year, $month);

        return view('report.region_indicator_progress.index', [
            'year' => $year,
            'month' => $month,
            'report_region_indicator' => $report_region_indicator
        ]);
    }


    public function cache(Request $request)
    {
        $year = $request->year;
        $month = $request->month;
        //先删除已经缓存的数据
        CacheInvoiceRegion::where(['year' => $year, 'month' => $month])->delete();

        //再添加数据
        $invoice_infos = InvoiceDetails::select(['sales_region_code', DB::raw('sum(total_price_no_tax) as amount')])
            ->where([
                'year' => $year,
                'month' => $month,
            ])->groupBy('sales_region_code')
            ->get();
        foreach ($invoice_infos as $invoice_info) {
            $model = new CacheInvoiceRegion();
            $model->year = $year;
            $model->month = $month;
            $model->sales_region_code = $invoice_info->sales_region_code;
            $model->amount = $invoice_info->amount;
            $model->save();
        }

        return ['status' => ResultInfo::SUCCESS];
    }


    public function export()
    {
        Excel::store(new ReportRegionIndicatorExport, '/export/大区指标进度汇总_' . date('Ymd_His', time()) . '.xlsx');
        return ['status' => ResultInfo::SUCCESS];
    }


    public function visual()
    {
        return view('report.region_indicator_progress.visual');
    }
}
